<?php
/**
 * 发现板块专用
 */

/**
 * 获取当前分类下的所有子类
 * @param  int $cid 分类ID
 * @return arr      所有子类ID数组
 */
function getTvdCatAllChildren($cid) {
    if (!empty($cid) && !is_array($cid)) {
        $cid = array($cid);
    }
    $cStr = implode(',', $cid);
    $sql = "SELECT cat_id FROM egg_tvd_cat WHERE parent_id IN ($cStr)";
    $cArr = $GLOBALS['db']->getCol($sql);
    if (!empty($cArr)) {
        if ($cArr2 = getTvdCatAllChildren($cArr)) {
            return array_merge($cArr, $cArr2);
        }
        return $cArr;
    }
    return false;
}

/**
 * 获取当前分类下的所有父类
 * @param  int $cid 分类ID
 * @return arr      所有子类ID数组
 */
function getTvdCatAllParent($cid) {
    if (!empty($cid) && !is_array($cid)) {
        $cid = array($cid);
    }
    $cStr = implode(',', $cid);
    $sql = "SELECT parent_id FROM egg_tvd_cat WHERE cat_id IN ($cStr)";
    $cArr = $GLOBALS['db']->getCol($sql);
    if (!empty($cArr)) {
        if ($cArr2 = getTvdCatAllParent($cArr)) {
            return array_unique(array_filter(array_merge($cArr, $cArr2)));
        }
        return array_unique(array_filter($cArr));
    }
    return false;
}

/**
 * 获取当前分类子类
 * @param  int $cid 分类ID
 * @return arr      所有子类ID数组
 */
function getTvdCatChildren($cid = 0) {
    $sql = "SELECT cat_id, cat_name FROM egg_tvd_cat WHERE parent_id = '$cid' ORDER BY sort_order ASC";
    $cArr = $GLOBALS['db']->getAll($sql);
    foreach ($cArr as $key => $value) {
        $value['url'] = getUrl('tvd_cat', $value['cat_id']);
        $cArr[$key] = $value;
    }
    return $cArr;
}

/**
 * 获取话题
 *
 * @access  private
 * @param   int     $size  //调取数量
 * @param   int     $page  //页码
 * @return  array
 */
function getTvdList(){
    /* 搜索词、品牌、分类 */
    $q   = !empty($_REQUEST['q']) ? htmlspecialchars(trim($_REQUEST['q'])) : '';
    $c   = !empty($_REQUEST['c']) ? intval($_REQUEST['c']) : 0;
    $page = !empty($_REQUEST['page']) ? intval($_REQUEST['page']): '1' ;

    /**
     * 初始化搜索条件
     */
    $where = "t.is_open = 1";
    /* 环境判断【分类(单选)】 */
    if (!empty($c)) {
        $cArr = getTvdCatAllChildren($c);
        $cArr[] = $c; // 将当前选择分类ID加进条件数组
        if (!empty($cArr)) {
            $cStr = implode(',', $cArr);
            /* 获取所有包含这些分类的goods_id */
            $sql = "SELECT tvd_id FROM egg_tvd_extcat WHERE cat_id IN ($cStr)";
            $tArr = DB()->getCol($sql);
            if (!empty($gArr)) {
                $tStr = implode(',', $tArr);
                $where .= " AND (t.cat_id IN($cStr) OR t.tvd_id IN($tStr))";
            } else {
                $where .= " AND t.cat_id IN($cStr)";
            }
        }
    }

    /* 如果存在搜索词 */
    if (!empty($q)) {
        $where .= " AND CONCAT(t.title, t.keywords, t.content) LIKE '%$q%'";
    }
    $sql =  " SELECT t.list_img, t.tvd_id, t.title, t.click, t.description, t.praise, c.cat_name, a.author_name, a.author_head FROM egg_tvd AS t LEFT JOIN egg_tvd_cat c ON c.cat_id = t.cat_id LEFT JOIN egg_tvd_author a ON a.author_id = t.author_id WHERE $where ORDER BY t.tvd_type DESC, t.ext_type DESC, sort DESC LIMIT " . ($page - 1) * 9 . ', 9';
    $tvdList = DB()->getAll($sql);
    if (!empty($tvdList)) {
        /* 获取用户关注过的主题 */
        if (!empty($_SESSION['user_id'])) {
            $sql =  " SELECT c.tvd_id FROM egg_tvd_collect AS c WHERE c.user_id = '{$_SESSION['user_id']}'";
            $collect = DB()->getCol($sql);
        } else {
            $collect = array();
        }
        /* 格式化 */
        foreach ($tvdList as $key => $value) {
            $value['url'] = getUrl('tvd', $value['tvd_id']);
            $value['list_img'] = getUrl('tvd_list_img', $value['list_img']);
            if (empty($value['author_head'])) {
                $value['author_head'] = __PUC__ . '/img/tvd/author.png';
            }
            if (empty($value['title_small'])) {
                $value['title_small'] = '#' . $value['cat_name'];
            }
            /* 判断是否已收藏 */
            if (in_array($value['tvd_id'], $collect)) $value['collect'] = true;
            $tvdList[$key] = $value;
        }
    }
    return $tvdList;
}

/**
 * 首页获取发现列表
 * @param  integer $start [description]
 * @param  integer $size  [description]
 * @return [type]         [description]
 */
function getIndexTvdList($start = 0, $size = 5) {
    /* 获取商品列表 */
    $sql =  " SELECT t.list_img, t.title_small, t.description, t.tvd_id, t.title, t.click, t.praise, c.cat_name, a.author_name, a.author_head FROM egg_tvd AS t LEFT JOIN egg_tvd_cat c ON c.cat_id = t.cat_id LEFT JOIN egg_tvd_author a ON a.author_id = t.author_id ORDER BY t.tvd_type DESC, t.ext_type DESC, sort DESC LIMIT $start, $size";
    $tvdList = DB()->getAll($sql);
    /* 获取用户关注 */
    if (!empty($_SESSION['user_id'])) {
        $sql =  " SELECT c.tvd_id FROM egg_tvd_collect AS c WHERE c.user_id = '{$_SESSION['user_id']}'";
        $collect = DB()->getCol($sql);
    } else {
        $collect = array();
    }
    if (!empty($tvdList)) {
        foreach ($tvdList as $key => $value) {
            $value['url'] = getUrl('tvd', $value['tvd_id']);
            $value['list_img'] = getUrl('tvd_list_img', $value['list_img']);
            if (empty($value['author_head'])) {
                $value['author_head'] = __PUC__ . '/img/tvd/author.png';
            }
            if (empty($value['title_small'])) {
                $value['title_small'] = '#' . $value['cat_name'];
            }
            /* 判断是否已收藏 */
            if (in_array($value['tvd_id'], $collect)) $value['collect'] = true;
            $tvdList[$key] = $value;
        }
    }
    return $tvdList;
}

/**
 * 获取详细内容
 * @param  int $id 发现ID
 * @return arr     发现数组
 */
function getTvdInfo($id) {
    /* 获取内容 */
    $sql = "SELECT cat_id, content, praise, share, list_img, title, description, keywords FROM egg_tvd WHERE tvd_id = '$id' AND is_open = 1";
    $info = DB()->getRow($sql);
    /* 获取关注人数 */
    $sql = "SELECT count(*) AS collectNum FROM egg_tvd_collect WHERE tvd_id = '$id'";
    $info['collectNum'] = DB()->getOne($sql);
    /* 获取评论人数 */
    $sql = "SELECT count(*) AS collectNum FROM egg_tvd_comment WHERE tvd_id = '$id'";
    $info['commentNum'] = DB()->getOne($sql);
    /* 用户登录时是否已经关注此信息 */
    if (!empty($_SESSION['user_id'])) {
        $sql = "SELECT count(*) AS iscollect FROM egg_tvd_collect WHERE tvd_id = '$id' AND user_id = '" . $_SESSION['user_id'] . "'";
        $info['iscollect'] = $GLOBALS['db']->getOne($sql);
    } else {
        $info['iscollect'] = 0;
    }
    return $info;
}

/**
 * 获取评论详细内容
 * @param  int  $id    发现ID
 * @param  int  $start 开始指数
 * @param  int  $size  获取条目数
 * @return arr         评论列表
 */
function getTvdComment($id, $start = 0, $size = 3) {
    /* 获取所有评论 */
    $sql = "SELECT * FROM egg_tvd_comment WHERE tvd_id = '$id' ORDER BY add_time DESC LIMIT $start, $size";
    $commentList = DB()->getAll($sql);
    foreach ($commentList as $key => $value) {
        $sql = "SELECT head_url FROM egg_user_info WHERE user_id = '$value[user_id]'";
        $commentList[$key]['imgUrl'] = getUrl('head_url', DB()->getOne($sql));
        /* 如果不存在则使用默认头像 */
        if (empty($commentList[$key]['imgUrl'])) {
            $commentList[$key]['imgUrl'] = __PUC__ . '/img/tvd/comt-head.png';
        }
    }
    return $commentList;
}

/**
 * 随机获取虚假评论
 */
function getFakeComment($rand = 15) {
    /* 获取用户名 */
    $uStr = file_get_contents(ROOT_PATH . '/includes/valTvdUser.php');
    $uArr = explode("\n", $uStr);
    $cStr = file_get_contents(ROOT_PATH . '/includes/valTvdComment.php');
    $cArr = explode("\n", $cStr);
    shuffle($uArr);
    shuffle($cArr);
    $arr['user'] = array_slice($uArr, 0, $rand);
    $arr['comment'] = array_slice($cArr, 0, $rand);
    return $arr;
}

/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @return  mix
 */
function tvd_cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0)
{
    static $res = NULL;

    if ($res === NULL)
    {
            $sql = "SELECT c.*, COUNT(s.cat_id) AS has_children, COUNT(a.tvd_id) AS aricle_num ".
               ' FROM ' . $GLOBALS['ecs']->table('tvd_cat') . " AS c".
               " LEFT JOIN " . $GLOBALS['ecs']->table('tvd_cat') . " AS s ON s.parent_id=c.cat_id".
               " LEFT JOIN " . $GLOBALS['ecs']->table('tvd') . " AS a ON a.cat_id=c.cat_id".
               " GROUP BY c.cat_id ".
               " ORDER BY parent_id, sort_order ASC";
            $res = $GLOBALS['db']->getAll($sql);
    }

    if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }

    $options = tvd_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

    /* 截取到指定的缩减级别 */
    if ($level > 0)
    {
        if ($cat_id == 0)
        {
            $end_level = $level;
        }
        else
        {
            $first_item = reset($options); // 获取第一个元素
            $end_level  = $first_item['level'] + $level;
        }

        /* 保留level小于end_level的部分 */
        foreach ($options AS $key => $val)
        {
            if ($val['level'] >= $end_level)
            {
                unset($options[$key]);
            }
        }
    }

    $pre_key = 0;
    foreach ($options AS $key => $value)
    {
        $options[$key]['has_children'] = 1;
        if ($pre_key > 0)
        {
            if ($options[$pre_key]['cat_id'] == $options[$key]['parent_id'])
            {
                $options[$pre_key]['has_children'] = 1;
            }
        }
        $pre_key = $key;
    }

    if ($re_type == true)
    {
        $select = '';
        foreach ($options AS $var)
        {
            $select .= '<option value="' . $var['cat_id'] . '" ';
            $select .= ' cat_type="' . $var['cat_type'] . '" ';
            $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
            $select .= '>';
            if ($var['level'] > 0)
            {
                $select .= str_repeat('&nbsp;', $var['level'] * 4);
            }
            $select .= htmlspecialchars(addslashes($var['cat_name'])) . '</option>';
        }

        return $select;
    }
    else
    {
        foreach ($options AS $key => $value)
        {
            $options[$key]['url'] = build_uri('tvd_cat', array('acid' => $value['cat_id']), $value['cat_name']);
        }
        return $options;
    }
}

/**
 * 过滤和排序所有文章分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function tvd_cat_options($spec_cat_id, $arr)
{
    static $cat_options = array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }

    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        while (!empty($arr))
        {
            foreach ($arr AS $key => $value)
            {
                $cat_id = $value['cat_id'];
                if ($level == 0 && $last_cat_id == 0)
                {
                    if ($value['parent_id'] > 0)
                    {
                        break;
                    }

                    $options[$cat_id]          = $value;
                    $options[$cat_id]['level'] = $level;
                    $options[$cat_id]['id']    = $cat_id;
                    $options[$cat_id]['name']  = $value['cat_name'];
                    unset($arr[$key]);

                    if ($value['has_children'] == 0)
                    {
                        continue;
                    }
                    $last_cat_id  = $cat_id;
                    $cat_id_array = array($cat_id);
                    $level_array[$last_cat_id] = ++$level;
                    continue;
                }

                if ($value['parent_id'] == $last_cat_id)
                {
                    $options[$cat_id]          = $value;
                    $options[$cat_id]['level'] = $level;
                    $options[$cat_id]['id']    = $cat_id;
                    $options[$cat_id]['name']  = $value['cat_name'];
                    unset($arr[$key]);

                    if ($value['has_children'] > 0)
                    {
                        if (end($cat_id_array) != $last_cat_id)
                        {
                            $cat_id_array[] = $last_cat_id;
                        }
                        $last_cat_id    = $cat_id;
                        $cat_id_array[] = $cat_id;
                        $level_array[$last_cat_id] = ++$level;
                    }
                }
                elseif ($value['parent_id'] > $last_cat_id)
                {
                    break;
                }
            }

            $count = count($cat_id_array);
            if ($count > 1)
            {
                $last_cat_id = array_pop($cat_id_array);
            }
            elseif ($count == 1)
            {
                if ($last_cat_id != end($cat_id_array))
                {
                    $last_cat_id = end($cat_id_array);
                }
                else
                {
                    $level = 0;
                    $last_cat_id = 0;
                    $cat_id_array = array();
                    continue;
                }
            }

            if ($last_cat_id && isset($level_array[$last_cat_id]))
            {
                $level = $level_array[$last_cat_id];
            }
            else
            {
                $level = 0;
            }
        }
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }

    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}


/**
 * 获得指定文章分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 *
 * @return void
 */
function get_tvd_children ($cat = 0)
{
    return db_create_in(array_unique(array_merge(array($cat), array_keys(tvd_cat_list($cat, 0, false)))), 'cat_id');
}

/**
 * 保存扩展分类
 * @param   int     $goods_id   商品编号
 * @param   array   $cat_list   分类编号数组
 * @return  void
 */
function handle_other_cat($tvd_id, $cat_list)
{
    /* 查询现有的扩展分类 */
    $sql = "SELECT cat_id FROM " . $GLOBALS['ecs']->table('tvd_extcat') .
            " WHERE tvd_id = '$tvd_id'";
    $exist_list = $GLOBALS['db']->getCol($sql);

    /* 删除不再有的分类 */
    $delete_list = array_diff($exist_list, $cat_list);
    if ($delete_list)
    {
        $sql = "DELETE FROM " . $GLOBALS['ecs']->table('tvd_extcat') .
                " WHERE tvd_id = '$tvd_id' " .
                "AND cat_id " . db_create_in($delete_list);
        $GLOBALS['db']->query($sql);
    }

    /* 添加新加的分类 */
    $add_list = array_diff($cat_list, $exist_list, array(0));
    foreach ($add_list AS $cat_id)
    {
        // 插入记录
        $sql = "INSERT INTO " . $GLOBALS['ecs']->table('tvd_extcat') .
                " (tvd_id, cat_id) " .
                "VALUES ('$tvd_id', '$cat_id')";
        $GLOBALS['db']->query($sql);
    }
}
